package cn.js189.uqc.task;

import cn.js189.common.constants.InvoiceConstant;
import cn.js189.common.util.helper.UUIDHelper;
import cn.js189.uqc.common.WxService;
import cn.js189.uqc.mapper.CheckInfoMapper;
import cn.js189.uqc.redis.RedisOperation;
import cn.js189.uqc.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 批量插卡到用户卡包定时任务
 */
@Slf4j
public class WxBatchInsertTask implements Runnable {

	@Resource
	private WxService wxService;
	@Resource
	private CheckInfoMapper checkInfoMapper;
	@Resource
	private RedisOperation redisOperation;

	public WxBatchInsertTask(WxService wxService, CheckInfoMapper checkInfoMapper,RedisOperation redisOperation) {
		this.wxService = wxService;
		this.checkInfoMapper = checkInfoMapper;
		this.redisOperation = redisOperation;
	}

	@Override
	public void run() {
		log.info("微信一次授权插卡定时任务启动...");

		// 用户app授权信息表关联订单详情,根据partyId查询出已经授权,并且已经开票完成并且未插卡的发票进行插卡操作
		List<Map<String,String>> invoiceIds = this.checkInfoMapper.selectAllOnceAuthSuccessInvoiceId();

		if (null != invoiceIds && !invoiceIds.isEmpty()) {
			log.info("微信一次授权插卡定时任务查询出数据:{}", invoiceIds.size());

			for (Map<String, String> map :invoiceIds) {
				String invoiceId = map.get("invoiceId");
				String partyId = map.get("partyId");
				String appId = map.get("appId");
				String orderId = map.get("orderId");
				log.info("发票【{}】已经授权完成,开始进行插卡操作!", invoiceId);

				// 用于屏蔽之前的插卡用户，之后可删除
				int count = this.checkInfoMapper.selectInvoiceTimeCount(invoiceId);
				if(count>0){
					log.info("微信一次授权插卡定时任务查询出数据在2023-2之前:{}", invoiceId);
					// 保存插卡次数
					this.wxService.saveInsertCount(invoiceId,partyId,orderId);
					continue;
				}
				// 加锁
				String lockValue = UUIDHelper.getUUID();
				String lockKey = InvoiceConstant.WX_CARD_INSERT_PREFIX + invoiceId;
				String lockResult = RedisUtil.tryLock(redisOperation, "一次授权电子发票插卡", lockKey, lockValue);

				// 获取锁失败
				if (!StringUtils.equals(lockResult, RedisUtil.LOCK_SUCCESS)) {
					continue;
				}
				try {
					// 一次授权插卡
					this.wxService.toInsertInvoice(invoiceId,partyId,appId, "once");
				} catch (Exception e) {
					log.info("发票【{}】一次授权插卡任务异常 {}", invoiceId, e.getMessage());
				}
				RedisUtil.unlock(redisOperation, "一次授权电子发票插卡", lockKey, lockValue);
			}
		}
	}
}
